import logging
from time import localtime

# --- module logger
logger = logging.getLogger(__name__)

def selDayTime(droid):
  today = localtime()

  droid.dialogCreateTimePicker(today.tm_hour, today.tm_min, True)
  droid.dialogShow()
  selectedTime = droid.dialogGetResponse().result
  if selectedTime is None:
      return None
  
  droid.dialogCreateDatePicker(today.tm_year, today.tm_mon, today.tm_wday)
  droid.dialogShow()
  selectedDate = droid.dialogGetResponse().result
  return None if selectedDate is None else (selectedTime["hour"] * 60 * 60 + selectedTime["minute"] * 60, selectedDate['day'])



def alert(droid,title,msg,labels):
  """Show an alert and up to three buttons""" 
  if len(labels) > 3:
    raise FatalError("You cannot have more than 3 buttons")
  droid.dialogCreateAlert(title,msg)  
  if len(labels)>0:
    droid.dialogSetPositiveButtonText(labels[0])
  if len(labels)>1:
    droid.dialogSetNeutralButtonText(labels[1])
  if len(labels)>2:
    droid.dialogSetNegativeButtonText(labels[2])
  droid.dialogShow()
  r =  droid.dialogGetResponse()
  logger.info(r)
  r = r.result
  droid.dialogDismiss()
  if 'which' in r:
    return ['positive','neutral','negative'].index(r['which'])
  return -1  # canceled with the back key
  
  
def text_input(droid,title,msg,labels,defaultText="",inputType=""):
  """Show an input dialog and up to three buttons""" 
  if len(labels) > 3:
    raise FatalError("You cannot have more than 3 buttons")
  droid.dialogCreateInput(title,msg,defaultText,inputType)  
  if len(labels)>0:
    droid.dialogSetPositiveButtonText(labels[0])
  if len(labels)>1:
    droid.dialogSetNeutralButtonText(labels[1])
  if len(labels)>2:
    droid.dialogSetNegativeButtonText(labels[2])
  droid.dialogShow()
  r =  droid.dialogGetResponse()
  logger.info(r)
  r = r.result  
  droid.dialogDismiss()
  if 'which' in r:
    return r['value'], ['positive','neutral','negative'].index(r['which'])
  return r['value'], -1  # canceled with the back key

  
def single_choice_list(droid,title,items,labels):
  """Show a single choice list and up to three buttons.
  Return True and the item number (0-based) if an list item is selected,
  False and button number if a button is selected, False -1 is back is pressed """ 
  if len(labels) > 3:
    raise FatalError("You cannot have more than 3 buttons")
  droid.dialogCreateAlert(title)  
  if len(labels)>0:
    droid.dialogSetPositiveButtonText(labels[0])
  if len(labels)>1:
    droid.dialogSetNeutralButtonText(labels[1])
  if len(labels)>2:
    droid.dialogSetNegativeButtonText(labels[2])
  droid.dialogSetItems(items)  
  droid.dialogShow()
  r =  droid.dialogGetResponse()
  droid.dialogDismiss()
  logger.info(r)
  r = r.result
  if 'item' in r:
    return True, r['item']
  elif 'which' in r:
    return False, ['positive','neutral','negative'].index(r['which'])
  return False, -1  # canceled with the back key

